<template>
  <el-dialog
    :visible.sync="dialog"
    :close-on-click-modal="false"
    :title="title"
    width="700px"
    :append-to-body="true"
    top="5px"
    @close="doClose"
  >
    <el-container>
      <div class="vendor-info-edit">
        <el-tabs v-model="activeName" type="card">
          <el-tab-pane label="文描供应商信息" name="vendor-info">
            <el-form ref="editForm" :model="pbVendorMappingInfo" :rules="rules" :inline="true" size="mini" label-width="auto" label-position="right">

              <el-row>
                <el-col :span="12">
                  <el-form-item size="mini" label="部门:" prop="deptNbr">
                    <el-select v-model="pbVendorMappingInfo.deptNbr" size="mini" placeholder="请选择" clearable filterable :disabled="editable" style="width: 200px;" @change="queryFinelineByDept">
                      <el-option v-for="item in parent.deptList" :key="item.value" :label="item.name" :value="item.value" />
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item size="mini" label="fineline号:" prop="selectedFinelineNbrs">
                    <el-select v-model="pbVendorMappingInfo.selectedFinelineNbrs" size="mini" placeholder="请选择" clearable filterable multiple :disabled="editable" style="width: 200px;">
                      <el-option label="全选" value="ALL" />
                      <el-option v-for="item in finelineOptions" :key="item.fineLineNbr" :label="item.fineLineName + '_' + item.fineLineNbr" :value="item.fineLineNbr" />
                    </el-select>
                  </el-form-item>
                </el-col>
              </el-row>

              <el-row>
                <el-col :span="24">
                  <!-- <span class="el-form-item__label">选择一个文描供应商</span> -->
                  <span class="el-form-item__label">{{ contentVendorDivTitle }}</span>
                  <div style="text-align: right">
                    <span>
                      <el-input v-model="params.vendorNbr" size="mini" placeholder="输入供应商号搜索" clearable :disabled="editable" style="width: 130px;" />
                    </span>
                    <span>
                      <el-input v-model="params.vendorName" size="mini" placeholder="输入供应商名称搜索" clearable :disabled="editable" style="width: 150px;" />
                    </span>
                    <span>
                      <el-button size="mini" round icon="el-icon-search" :disabled="editable" @click="toQuery" />
                      <el-button size="mini" round icon="el-icon-refresh" :disabled="editable" @click="resetParams" />
                    </span>
                  </div>
                  <div style="padding-top: 5px">
                    <el-table
                      ref="contentVendorTab"
                      :data="data"
                      stripe
                      size="small"
                      border
                      style="width: 100%;"
                      :row-key="getRowKeys"
                      @row-click="rowClick"
                      @selection-change="handleSelectionChange"
                    >
                      <el-table-column :reserve-selection="true" type="selection" align="center" width="55" />
                      <el-table-column :show-overflow-tooltip="true" label="流水号" prop="id" />
                      <el-table-column :show-overflow-tooltip="true" label="供应商号" prop="vendorNbr" />
                      <el-table-column :show-overflow-tooltip="true" label="供应商名称" prop="vendorName" />
                    </el-table>
                    <!--分页组件-->
                    <el-pagination
                      v-if="total > 10"
                      :total="total"
                      :current-page.sync="currentPage"
                      :page-sizes="[5, 10]"
                      style="margin-top: 8px;"
                      layout="total, prev, pager, next, sizes"
                      @size-change="sizeChange"
                      @current-change="pageChange"
                    />
                  </div>
                </el-col>
              </el-row>

            </el-form>
          </el-tab-pane>
        </el-tabs>
      </div>
    </el-container>
    <template>
      <div slot="footer" class="dialog-footer">
        <el-button size="mini" type="text" @click="doClose()">取消</el-button>
        <el-button v-if="currentOperate === 'ADD'" size="mini" type="primary" @click="doSave('ADD')">新增</el-button>
        <el-button v-if="currentOperate === 'EDIT'" size="mini" type="primary" @click="doSave('UPDATE')">修改</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script>
import Validate from './js/validate'
import Rule from './js/rule'
import { emptyPBVendorMappingInfo } from './js/variable'
import { add, update } from '@/api/coi/configuration/pb-vendor-mapping/pb-vendor-mapping'
import { queryFinelineByDept } from '@/api/coi/configuration/pb-vendor-mapping/fineline-data'
import { messageShowTool } from '@/utils/messageUtil'
import initData from '@/api/coi/commonInitData'

export default {
  mixins: [initData],
  props: {
    parent: {
      type: Object,
      default: null
    }
  },
  data() {
    return {
      dialog: false,
      title: '',
      currentObj: this,
      currentOperate: null,
      contentVendorDivTitle: '请选择一个文描供应商',
      activeName: 'vendor-info',
      cityOptions: null,
      pbVendorMappingInfo: this.emptyPBVendorMappingInfo(),
      rules: {},
      finelineOptions: [{}],

      rule: new Rule(this),
      validate: new Validate(this)
    }
  },
  computed: {
    editable: function() {
      return this.currentOperate === 'VIEW'
    }
  },
  watch: {
    'pbVendorMappingInfo.selectedFinelineNbrs': {
      handler(n, o) {
        if (!o) {
          return
        }
        const newIndex = n.indexOf('ALL')
        const oldIndex = o.indexOf('ALL')
        // 新的选择中勾选了‘全选’，则只选择‘全选’
        if (newIndex !== -1 && oldIndex === -1 && n.length > 1) {
          this.pbVendorMappingInfo.selectedFinelineNbrs = ['ALL']
        }
        // 新的选择中有‘全选’，并且之前也勾选了‘全选’，且选择数量大于1，则移除掉‘全选’
        if (newIndex !== -1 && oldIndex !== -1 && n.length > 1) {
          this.pbVendorMappingInfo.selectedFinelineNbrs.splice(newIndex, 1)
        }
      }
    }
  },
  created() {
    this.$nextTick(() => {
      this.init()
    })
  },
  mounted() {
    this.$nextTick(() => {
      this.rule.initRules()
    })
  },
  methods: {
    messageShowTool,
    emptyPBVendorMappingInfo,
    // 关闭
    doClose: function() {
      this.resetFields()
      // 清楚表单勾选缓存
      this.$refs.contentVendorTab.clearSelection(this.multipleSelection)
      this.dialog = false
    },
    doCloseRefresh() {
      this.doClose()
      this.parent.resetForm()
    },
    // 对整个表单进行重置，将所有字段值重置为初始值并移除校验结果
    resetFields() {
      if (this.$refs.editForm) {
        this.$refs.editForm.clearValidate()
        this.$refs.editForm.resetFields()
      }
    },
    // 通过部门查询所有fileline信息
    queryFinelineByDept(val) {
      this.finelineOptions = []
      this.pbVendorMappingInfo.selectedFinelineNbrs = []
      if (!val) {
        return
      }
      queryFinelineByDept(val).then(res => {
        if (res && res.result) {
          this.finelineOptions = res.result
        } else {
          this.finelineOptions = []
        }
      })
    },
    // 编辑
    doSave(oprationType) {
      const _this = this
      let msg = '确认新增当前PB文描供应商信息吗？'
      if (oprationType !== 'ADD') {
        msg = '确认修改当前PB文描供应商信息吗？'
      }
      if (!this.pbVendorMappingInfo.contentVendorId) {
        _this.messageShowTool('请选择一个文描供应商', 'warning')
        return
      }
      this.$refs.editForm.validate(valid => {
        if (valid) {
          this.$confirm(msg, '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            this.savePBContentVendorInfo(_this, oprationType)
          })
        } else {
          _this.messageShowTool('校验失败', 'warning')
        }
      })
    },
    // 保存PB文描供应商映射关系
    savePBContentVendorInfo(_this, oprationType) {
      if (_this.pbVendorMappingInfo.selectedFinelineNbrs.length === 1 && _this.pbVendorMappingInfo.selectedFinelineNbrs[0] === 'ALL') {
        const selectedFinelines = []
        _this.finelineOptions.forEach(ele => {
          if (ele) {
            selectedFinelines.push(ele.fineLineNbr)
          }
        })
        _this.pbVendorMappingInfo.selectedFinelineNbrs = selectedFinelines
      }
      if (oprationType === 'ADD') { // 新增
        add(_this.pbVendorMappingInfo).then(res => {
          if (res && res.code === '0') {
            _this.messageShowTool('新增成功！', 'success')
            _this.doCloseRefresh()
          }
        })
      } else { // 修改
        update(_this.pbVendorMappingInfo).then(res => {
          if (res && res.code === '0') {
            _this.messageShowTool('修改成功！', 'success')
            _this.doCloseRefresh()
          }
        })
      }
    },
    // 初始化空数据
    initPBVendorMappingData() {
      this.pbVendorMappingInfo = this.emptyPBVendorMappingInfo()
    },
    // 表格查询相关方法
    beforeInit() {
      this.url = process.env.VUE_APP_BASE_API7 + '/content-vendor/queryPage'
      this.params.pageNum = this.page
      this.params.pageSize = this.size
      return true
    },
    toQuery() {
      this.page = 0
      this.currentPage = 1
      this.$refs.contentVendorTab.clearSelection()
      this.init()
    },
    resetParams() {
      this.params = {}
      this.toQuery()
    },
    getRowKeys(row) {
      return row.id
    },
    rowClick(row) {
      this.$refs.contentVendorTab.clearSelection()
      this.$refs.contentVendorTab.toggleRowSelection(row, true)
    },
    // 列表多选框触发
    handleSelectionChange(val) {
      if (val.length > 1) {
        this.$refs.contentVendorTab.clearSelection()
        this.$refs.contentVendorTab.toggleRowSelection(val.pop())
      } else {
        this.multipleSelection = val.pop()
      }
      if (this.multipleSelection) {
        this.pbVendorMappingInfo.contentVendorId = this.multipleSelection.id
      } else {
        this.pbVendorMappingInfo.contentVendorId = null
      }
    },
    // 清空表单选择
    clearTableSelection() {
      this.$refs.contentVendorTab.clearSelection(this.multipleSelection)
    }
  }
}
</script>
<style scoped>
  .vendor-info-edit {
    padding-top: 5px;
    width: 100%
  }
  .vendor-info-edit >>> .el-form-item--mini.el-form-item {
    margin: 0px;
    padding: 0px 0px 12px 0px;
  }
  .vendor-info-edit >>> .el-form >>> .el-row {
    margin-bottom: 10px;
  }
</style>
